package com.caiya.service.impl;

import com.caiya.cart.CartRequest;
import com.caiya.cart.dto.user.CartUserInfoDto;
import com.caiya.cart.entity.CartUser;
import com.caiya.cart.vo.user.CartUserAddVo;
import com.caiya.cart.vo.user.CartUserInfoVo;
import com.caiya.cart.vo.user.CartUserListVo;
import com.caiya.cart.vo.user.CartUserUpdateVo;
import com.caiya.mapper.CartUserMapper;
import com.caiya.service.UserCartService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Created by Administrator on 2018/11/28 0028.
 */
@Service
public class UserCartServiceImpl implements UserCartService {

    @Autowired
    private CartUserMapper cartUserMapper;

    @Override
    public PageInfo<CartUser> list(CartUserListVo cartUserListVo) {
        PageHelper.startPage(cartUserListVo.getPageNum(),cartUserListVo.getPageSize());
        List<CartUser> list = cartUserMapper.list(cartUserListVo);
        PageInfo<CartUser> info = new PageInfo<>(list);
        return info;
    }

    @Override
    public int add(CartUserAddVo cartUserAddVo) throws Exception {
        if (cartUserAddVo.getName()==null || cartUserAddVo.getName().trim().isEmpty()){
            throw new Exception("请填写姓名");
        }
        int i = cartUserMapper.isUserExist(cartUserAddVo.getName());
        if (i>0){
            throw new Exception("用户已存在");
        }

        CartUser user = new CartUser();
        user.setName(cartUserAddVo.getName());
        user.setPhone(cartUserAddVo.getPhone());
        user.setUserAddress(cartUserAddVo.getUserAddress());
        user.setUserImg(cartUserAddVo.getUserImg());
        return cartUserMapper.insert(user);
    }

    @Override
    public int update(CartUserUpdateVo cartUserUpdateVo) throws Exception {
        if (cartUserUpdateVo.getName()==null || cartUserUpdateVo.getName().trim().isEmpty()){
            throw new Exception("请填写姓名");
        }
        String s = cartUserMapper.selectUserNameById(cartUserUpdateVo.getId());
        if (s.equals(cartUserUpdateVo.getName())){
            cartUserUpdateVo.setName(null);
        }else {
            int i = cartUserMapper.isUserExist(cartUserUpdateVo.getName());
            if (i>0){
                throw new Exception("用户已存在");
            }
        }
        return cartUserMapper.update(cartUserUpdateVo);
    }

    @Override
    public CartUserInfoDto info(CartUserInfoVo cartUserInfoVo) {
        return cartUserMapper.info(cartUserInfoVo);
    }
}
